package com.fzl.spring_chatroom.service;

import com.fzl.spring_chatroom.model.dao.FriendRequest;
import com.fzl.spring_chatroom.model.mapper.FriendRequestMapper;
import com.fzl.spring_chatroom.model.mapper.FriendMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import com.fzl.spring_chatroom.controller.WebSocketController;

import java.util.List;

@Service
public class FriendRequestService {

    @Autowired
    private FriendRequestMapper friendRequestMapper;
    @Autowired
    private FriendMapper friendMapper;
    @Autowired(required = false)
    private SimpMessagingTemplate messagingTemplate; // 用于WebSocket推送

    public boolean sendFriendRequest(Integer fromUserId, Integer toUserId) {
        if (friendMapper.isFriend(fromUserId, toUserId) > 0) {
            return false;
        }
        if (friendRequestMapper.selectPending(fromUserId, toUserId) != null) {
            return false;
        }
        FriendRequest request = new FriendRequest();
        request.setFromUserId(fromUserId);
        request.setToUserId(toUserId);
        request.setStatus("pending");
        friendRequestMapper.insert(request);
        // 实时推送给对方
        WebSocketController.sendFriendRequest(toUserId, request);
        return true;
    }

    public List<FriendRequest> getPendingRequests(Integer userId) {
        return friendRequestMapper.selectPendingByUserId(userId);
    }

    public boolean handleRequest(Integer requestId, String action) {
        System.out.println("handleRequest参数: requestId=" + requestId + ", action=" + action);
        FriendRequest request = friendRequestMapper.selectById(requestId);
        System.out.println("查到的request: " + request);
        if (request == null || !"pending".equals(request.getStatus())) {
            System.out.println("请求不存在或已处理: " + requestId);
            return false;
        }
        if ("accept".equals(action)) {
            System.out.println("同意好友请求，插入好友关系: " + request.getFromUserId() + " <-> " + request.getToUserId());
            friendMapper.addFriend(request.getFromUserId(), request.getToUserId());
            friendMapper.addFriend(request.getToUserId(), request.getFromUserId());
            friendRequestMapper.updateStatus(requestId, "accepted");
            System.out.println("已更新好友请求状态为accepted");
            WebSocketController.sendFriendAccept(request.getFromUserId(), request);
            WebSocketController.sendFriendAccept(request.getToUserId(), request);
            System.out.println("已通知双方成为好友");
        } else if ("reject".equals(action)) {
            System.out.println("拒绝好友请求: " + requestId);
            friendRequestMapper.updateStatus(requestId, "rejected");
            System.out.println("已更新好友请求状态为rejected");
        } else {
            System.out.println("未知action: " + action);
        }
        return true;
    }
}